/********************************************************************
	created:	2012/03/26
	filename: 	Dx9FxMaterialWrapper.cpp
	author:		Mwolf
	
	purpose:	
*********************************************************************/

#include "StdAfx.h"
#include "Dx9FxMaterialWrapper.h"
#include "../DX9SharedLayer/DX9Device.h"
#include <assert.h>

struct Dx9FXMaterial
{
	ID3DXEffect*	Effect;
};

using namespace System::Runtime::InteropServices; // for class Marshal

namespace DX9ToolManaged
{
	Dx9FxMaterialWrapper::Dx9FxMaterialWrapper()
		: m_Impl(NULL)
	{
	}

	Dx9FxMaterialWrapper::~Dx9FxMaterialWrapper()
	{
		UnloadEffect();
	}

	bool Dx9FxMaterialWrapper::LoadEffectFromFile( System::String^ filename )
	{
		char* pName = (char*)(void*)Marshal::StringToHGlobalAnsi(filename);
		m_Impl = Dx9FX_LoadEffectFromFile(pName);

		return (m_Impl != NULL);
	}

	void Dx9FxMaterialWrapper::UnloadEffect()
	{
		if (m_Impl)
		{
			Dx9FX_UnloadEffect(m_Impl);
			m_Impl = NULL;
		}
	}

	void Dx9FxMaterialWrapper::UpdateNonSharedMatrices()
	{
		if (!m_Impl)
			return;

		D3DXMATRIX matWorld;
		D3DXMatrixIdentity( &matWorld );

		Dx9FX_UpdateNonSharedMatrices(m_Impl, &matWorld);
	}

	bool Dx9FxMaterialWrapper::IsAvailable()
	{
		return (m_Impl != NULL);
	}

	UINT Dx9FxMaterialWrapper::Begin()
	{
		assert(m_Impl->Effect);

		UINT PassCount;
		m_Impl->Effect->Begin( &PassCount, 0 );
		return PassCount;
	}

	void Dx9FxMaterialWrapper::End()
	{
		assert(m_Impl->Effect);
		m_Impl->Effect->End();
	}

	void Dx9FxMaterialWrapper::BeginPass( UINT Pass )
	{
		assert(m_Impl->Effect);
		m_Impl->Effect->BeginPass(Pass);
	}

	void Dx9FxMaterialWrapper::EndPass()
	{
		assert(m_Impl->Effect);
		m_Impl->Effect->EndPass();
	}

	System::String^ Dx9FxManager::GetLastErrorString()
	{
		return gcnew System::String(Dx9FX_GetLastErrorString());
	}

	void Dx9FxManager::UpdateSharedMatrices()
	{
		D3DXVECTOR3 vEyePt( 0.0f, 5.0f, -5.0f );
		D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
		D3DXVECTOR3 vUpVec( 0.0f, 1.0f, 0.0f );

		D3DXMATRIX matView;
		D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );

		D3DXMATRIX matProj;
		D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI / 4, API_D3D_DEVICE().GetScreenAspect(), 1.f, 100.f );

		Dx9FX_UpdateSharedMatrices( &matView, &matProj );
	}

}
